﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEngine;
using System;
using System.Reflection;

[RequireComponent(typeof(RectTransform))]
public class HoverInformation : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    public Component component;
    public string property;
    RectTransform rectTransform;
    public string information
    {
        get
        {
            if (setInformation != null)
            {
                return setInformation();
            }
            return string.Empty;
        }
    }

    public delegate string SetInformation();
    public event SetInformation setInformation;
    private void Start()
    {
        rectTransform = GetComponent<RectTransform>();
    }
    public void BindInformation(SetInformation setInformation)
    {
        this.setInformation += setInformation;
    }
    public void OnPointerEnter(PointerEventData eventData)
    {
        InformationText.ShowInformation(GetString(),rectTransform);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        InformationText.Exit();
    }

    string GetString()
    {
        string value = string.Empty;
        PropertyInfo pi = component.GetType().GetProperty(property);
        if (pi != null)
        {
            value = pi.GetValue(component, null) as string;
        }
        else
        {
            FieldInfo fi = component.GetType().GetField(property);
            value = fi.GetValue(component) as string;
        }

        return value;
    }
}

